package com.qijian.mold.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.mold.domain.dto.SelectMoldDto;
import com.qijian.mold.domain.entity.*;
import com.qijian.mold.domain.param.mold.CreateMoldParam;
import com.qijian.mold.domain.param.mold.SelectMoldParam;
import com.qijian.mold.domain.param.mold.UpdateMoldParam;
import com.qijian.mold.domain.vo.mold.MoldDetailsVo;
import com.qijian.mold.domain.vo.mold.MoldListVo;
import com.qijian.mold.domain.vo.moldChangeLog.ChangeLogListVo;
import com.qijian.mold.enums.MoldChangeLogTypesEnum;
import com.qijian.mold.enums.MoldChangeStatusEnum;
import com.qijian.mold.enums.MoldChangeTaskTypeEnum;
import com.qijian.mold.enums.MoldStatusEnum;
import com.qijian.mold.mapper.MoldMapper;
import com.qijian.mold.repository.*;
import com.qijian.mold.service.MoldChangeLogService;
import com.qijian.mold.service.MoldService;
import com.qijian.mold.util.IdGenerator;
import com.qijian.system.mapper.SysUserMapper;
import org.apache.http.util.Asserts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模具仓库
 *
 * @author anni.zhu
 * @author anni.zhu@king-v.com
 * Created in 2025/3/29 17:25
 */
@Service
public class MoldServiceImpl implements MoldService {

    @Autowired
    private MoldRepository moldRepository;
    @Autowired
    private MoldEqpMpRepository moldEqpMpRepository;
    @Autowired
    private TaskChangeDetailsRepository taskChangeDetailsRepository;
    @Autowired
    private MoldChangeTaskRepository taskRepository;

    /**
     * 创建模具仓库
     * @param param
     */
    @Override
    public void create(CreateMoldParam param) {
        Mold mold = new Mold();
        BeanUtils.copyProperties(param, mold);
        mold.setId(IdGenerator.SNOW.generate());
        mold.setStatus(MoldStatusEnum.FREE.getId());
        if (!moldRepository.save(mold)){
            throw new ServiceException("创建模具仓库失败");
        }
    }

    /**
     * 修改模具仓库
     * @param param
     */
    @Override
    public void update(UpdateMoldParam param) {
        Mold mold = moldRepository.getById(param.getId());
        if (mold == null){
            throw new ServiceException("模具仓库不存在");
        }
        BeanUtils.copyProperties(param, mold);
        if (!moldRepository.updateById(mold)){
            throw new ServiceException("修改模具仓库失败");
        }
    }

    /**
     * 删除模具仓库
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Mold mold = moldRepository.getById(id);
        if (mold == null){
            throw new ServiceException("模具仓库不存在");
        }

        List<MoldEqpMp> moldEqpMps = moldEqpMpRepository.getBaseMapper().selectList(new LambdaQueryWrapper<MoldEqpMp>()
                .eq(MoldEqpMp::getMoldId, id)
                .eq(MoldEqpMp::getIsDel, 0));
        if (CollectionUtil.isNotEmpty(moldEqpMps)){
            List<Long> eqpIds = moldEqpMps.stream().map(MoldEqpMp::getEqpId).collect(Collectors.toList());
            throw new ServiceException("模具仓库已被设备绑定，设备ID：" + JSONArray.toJSONString(eqpIds));
        }

        //检查模具是否被设备绑定
        if (!moldRepository.removeById(id)){
            throw new ServiceException("删除模具仓库失败");
        }
    }

    @Override
    public MoldDetailsVo getById(Long id) {
        Mold mold = moldRepository.getById(id);
        MoldDetailsVo moldDetailsVo = new MoldDetailsVo();
        if (mold != null){
            BeanUtils.copyProperties(mold, moldDetailsVo);
            String moldStatus = getMoldStatus(mold);
            moldDetailsVo.setMoldStatus(moldStatus);
        }
        return moldDetailsVo;
    }

    String getMoldStatus(Mold mold) {
        if (mold.getStatus() == MoldStatusEnum.FREE.getId()) {
            return "正常";
        } else if (mold.getStatus() == MoldStatusEnum.IN_PROGRESS.getId()) {
            //检查模具当前在哪一个阶段
            TaskChangeDetails taskChangeDetails = taskChangeDetailsRepository.getBaseMapper().selectOne(
                    new LambdaQueryWrapper<TaskChangeDetails>()
                            .eq(TaskChangeDetails::getMoldId, mold.getId())
                            .eq(TaskChangeDetails::getIsDel, 0)
                            .orderByDesc(TaskChangeDetails::getCreateTime)
                            .last("limit 1"));
            if (taskChangeDetails != null) {
                MoldChangeTask task = taskRepository.getById(taskChangeDetails.getTaskId());
                if (task != null) {
                    if (task.getType() == MoldChangeTaskTypeEnum.UP.getId()) {
                        if (task.getStatus()== MoldChangeStatusEnum.IN_PROGRESS.getId()) {
                            return "上模";
                        } else if (task.getStatus() == MoldChangeStatusEnum.COMPLETED.getId()) {
                            return "使用中";
                        } else {
                            return "未知状态";
                        }
                    } else {
                        if (task.getStatus()==MoldChangeStatusEnum.IN_PROGRESS.getId()) {
                            return "下模";
                        } else if (task.getStatus() == MoldChangeStatusEnum.COMPLETED.getId()) {
                            return "正常";
                        } else {
                            return "未知状态";
                        }
                    }
                } else {
                    return "未知状态";
                }
            }
        }  else {
            return "未知状态";
        }
        return "未知状态";
    }

    @Override
    public Page<MoldListVo> selectByPage(SelectMoldParam param) {
        SelectMoldDto dto = new SelectMoldDto();
        BeanUtils.copyProperties(param, dto);
        Page<MoldListVo> page = moldRepository.selectByPage(dto);
        return page;
    }

    @Override
    public void importMoldList(MultipartFile file) {
        Asserts.check(file != null && !file.isEmpty(), "文件为空，无法导入");
        List<CreateMoldParam> list = null;
        try {
            list = new ExcelUtil<>(CreateMoldParam.class).importExcel(file.getInputStream());
        } catch (Exception e) {
            throw new ServiceException("E01:文件导入异常,err:[{" + e.getStackTrace() + "}]");
        }
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("E02:文件内容为空，无法导入");
        }


        List<Mold> moldList = new ArrayList<>();
        for (CreateMoldParam param : list) {
            Mold mold = new Mold();
            BeanUtils.copyProperties(param, mold);
            mold.setId(IdGenerator.SNOW.generate());
            mold.setStatus(MoldStatusEnum.FREE.getId());
            moldList.add(mold);
        }
        if (!moldRepository.saveBatch(moldList)){
            throw new ServiceException("E03:导入失败");
        }
    }
}
